package com.bank.ui.admin;

import com.bank.dao.CardDAO;
import com.bank.entity.Card;
import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class QueryCardDialog extends JDialog {
    private List<Card> searchResult;

    public QueryCardDialog() {
        setTitle("银行卡查询");
        setSize(500, 300);
        setLocationRelativeTo(null);
        setModal(true);

        // 主面板使用GridBagLayout
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 卡号查询
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("卡号:"), gbc);

        gbc.gridx = 1;
        JTextField cardIdField = new JTextField(20);
        panel.add(cardIdField, gbc);

        // 客户ID查询
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("客户ID:"), gbc);

        gbc.gridx = 1;
        JTextField customerIdField = new JTextField(20);
        panel.add(customerIdField, gbc);

        // 日期范围查询 - 修改为单个输入框
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("开户日期:"), gbc);

        gbc.gridx = 1;
        // 添加提示文本
        JTextField dateField = new JTextField(20);
        dateField.setToolTipText("格式: yyyy-MM-dd 或 yyyy-MM-dd至yyyy-MM-dd");
        panel.add(dateField, gbc);

        // 按钮区域
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        JPanel buttonPanel = new JPanel();
        JButton searchButton = new JButton("查询");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(searchButton);
        buttonPanel.add(cancelButton);
        panel.add(buttonPanel, gbc);

        // 查询逻辑
        searchButton.addActionListener(e -> {
            String cardId = cardIdField.getText().trim();
            String customerIdStr = customerIdField.getText().trim();
            String dateRange = dateField.getText().trim();

            try {
                CardDAO dao = new CardDAO();

                if (!cardId.isEmpty()) {
                    Card card = dao.getCardByID(cardId);
                    if (card != null) {
                        searchResult = new ArrayList<>();
                        searchResult.add(card);
                    } else {
                        searchResult = new ArrayList<>();
                    }
                } else if (!customerIdStr.isEmpty()) {
                    int customerId = Integer.parseInt(customerIdStr);
                    searchResult = dao.getCardsByCustomerId(customerId);
                } else if (!dateRange.isEmpty()) {
                    // 解析日期范围
                    Date startDate = null;
                    Date endDate = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    sdf.setLenient(false); // 严格模式

                    // 检查是否包含分隔符"至"
                    if (dateRange.contains("至")) {
                        String[] dates = dateRange.split("至");
                        if (dates.length != 2) {
                            JOptionPane.showMessageDialog(
                                    QueryCardDialog.this,
                                    "日期范围格式错误！请使用：开始日期至结束日期",
                                    "日期错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                            return;
                        }
                        String startDateStr = dates[0].trim();
                        String endDateStr = dates[1].trim();

                        // 解析开始日期
                        if (!startDateStr.isEmpty()) {
                            try {
                                startDate = sdf.parse(startDateStr);
                            } catch (ParseException ex) {
                                JOptionPane.showMessageDialog(
                                        QueryCardDialog.this,
                                        "开始日期格式错误！请使用 yyyy-MM-dd 格式",
                                        "日期错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                                return;
                            }
                        }

                        // 解析结束日期
                        if (!endDateStr.isEmpty()) {
                            try {
                                endDate = sdf.parse(endDateStr);
                            } catch (ParseException ex) {
                                JOptionPane.showMessageDialog(
                                        QueryCardDialog.this,
                                        "结束日期格式错误！请使用 yyyy-MM-dd 格式",
                                        "日期错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                                return;
                            }
                        }

                        // 检查日期范围是否合理
                        if (startDate != null && endDate != null && startDate.after(endDate)) {
                            JOptionPane.showMessageDialog(
                                    QueryCardDialog.this,
                                    "开始日期不能晚于结束日期！",
                                    "日期范围错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                            return;
                        }
                    } else {
                        // 单个日期查询
                        try {
                            startDate = sdf.parse(dateRange);
                            endDate = startDate; // 开始和结束设为同一天
                        } catch (ParseException ex) {
                            JOptionPane.showMessageDialog(
                                    QueryCardDialog.this,
                                    "日期格式错误！请使用 yyyy-MM-dd 格式",
                                    "日期错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                            return;
                        }
                    }

                    // 执行日期范围查询
                    searchResult = dao.getCardsByOpenDateRange(startDate, endDate);
                } else {
                    JOptionPane.showMessageDialog(this, "请输入查询条件", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                if (searchResult == null || searchResult.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "未找到匹配的银行卡", "查询结果", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    dispose();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "客户ID必须是数字", "格式错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dispose());

        add(panel);
    }

    public List<Card> getSearchResult() {
        return searchResult;
    }
}